//
// Created by zarra on 2017/2/9.
//

#include "AnalyzeContext.h"
#include "document.h"
#include "project.h"
#include "word.h"
#include "wordposition.h"

TA::AnalyzeContext::AnalyzeContext(QObject *parent) : QObject(parent) {

}

void TA::AnalyzeContext::appendStatement(const TA::Statement *statement, int maxWordLength) {
    if (CHINESE == statement->getType()) {
        for (int i = 1; i <= maxWordLength; ++i) {
            appendStatementChinese(statement,i);
        }
    }else{
        appendStatementPrivate(statement);
    }
}

void TA::AnalyzeContext::appendStatement(const TA::StatementRawPtrArray &statements, int maxWordLength) {
    for (auto it = statements.begin(); it != statements.end(); it++) {
        appendStatement(*it, maxWordLength);
    }
}

TA::Word *TA::AnalyzeContext::fetchWord(const QString &word,int begin) {
    WordRawPtr result = nullptr;
    if (wordCache.find(word) == wordCache.end()) {
        Word *w = nullptr;
        Project* project = getDoc()->getProject();
        w = project->findWord(word);
        if (w == nullptr) {
            w = new Word(project);
            w->setWord(word);
            w->setStatus(UNCHECKED);
            project->getWords()->push_back(w);
        }
        wordCache[word] = w;
        getDoc()->getWords()->push_back(w);
    }
    result = wordCache[word];

    WordPosition* position = new WordPosition(result);

    position->setDocument(getDoc());
    position->setBeginPos(begin);
    position->setWord(result);

    result->getPositions().push_back(position);

    qDebug()<< "size:"<<result->getPositions().size();

    return result;
}

TA::WordCache *TA::AnalyzeContext::getWordCache() {
    return (TA::WordCache *) &(this->wordCache);
}

void TA::AnalyzeContext::appendStatementPrivate(const TA::Statement *statement) {
    Word *word = fetchWord(statement->getText(),statement->getBeginPos());
    word->setType(statement->getType());


}

void TA::AnalyzeContext::appendStatementChinese(const TA::Statement *statement, int wordLength) {
    QString text = statement->getText();
    int length = text.length();
    int pos = 0;
    int begin = statement->getBeginPos();
    while (pos < length && pos + wordLength - 1 < length) {
        QString subString = text.mid(pos, /*pos+*/ wordLength);

        Word *word = fetchWord(subString,begin+pos);
        word->setType(statement->getType());

        pos++;

    }
}

TA::Document *TA::AnalyzeContext::getDoc() const {
    return doc;
}

void TA::AnalyzeContext::setDoc(TA::Document *doc) {
    AnalyzeContext::doc = doc;
}
